﻿using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using ProgressControls;
using SCResources.BusinissLayer;
using SCResources.General;
using SCResources.ImdbSerieService;
using Serie_Counter.Code;
using Serie_Counter.Presentatie;
using SCResources.Interfaces;
using Serie = SCResources.General.Serie;

namespace Serie_Counter.Forms
{
    public partial class SerieForm : Form
    {
        //old form changeset: 13116
        //this is the remake.
        private ISeriesData seriesData;
        private int id;
        private SerieAirInfo airInfo;

        private ImdbServices imdbServices;
        private SeriesResultset seriesResultset;

        private int season;
        private int episode;
        private ProgressIndicator progressIndicator;

        //update vars
        private SerieWrapper serie;


        private SelectedCollection selectedCollection;
        private reDrawScreen reDrawScreen;
        private MemoryStream coverStream;


        public SerieWrapper Serie
        {
            get
            {
                return serie;
            }
        }

        /// <summary>
        /// Constructor for SerieForm
        /// </summary>
        /// <param name="seriesData">Database methode</param>
        /// <param name="id">Serie Id in DB, if -1 => new serie</param>
        public SerieForm(ISeriesData seriesData, int id = -1) // SelectedCollection selectedCollection = SelectedCollection.Active)
        {
            InitializeComponent();
            if (id != -1) iniContent();

            this.seriesData = seriesData;
            this.id = id;

            progressIndicator = new ProgressIndicator();
            progressIndicator.Size = new Size(20, 20);

            imdbServices = new ImdbServices();
            imdbServices.FoundSeries += new ImdbServices.FoundSeriesEventHandler(imdbServices_FoundSeries);




            //this.selectedCollection = selectedCollection;
            //textBoxTitel.Leave += new EventHandler(FindCover);
            //pictureBoxCover.Image = Image.FromFile(GeneralVars.DEFAULT_COVER_PATH);

            //ToolTip checkboxTooltip = new ToolTip();
            //checkboxTooltip.SetToolTip(checkBoxSaveCover,"When checked, the cover will be saved when adding the serie.");

            //ToolTip frequencyToolTip = new ToolTip();
            //frequencyToolTip.SetToolTip(textBoxFrequency, "Give a number of days");
            //this.Text = "Add serie";

        }

        private void iniContent()
        {
            serie = seriesData.Get(id);
            airInfo = serie.AirInfo;

            //base info
            textBoxTitel.Text = serie.Title;
            textBoxLocalDir.Text = serie.LocalDirectory;
            if (serie.CoverPath != null)
            {
                try
                {
                    pictureBoxCover.Image = Image.FromFile(serie.CoverPath); //todo: change methode => image can't be eraesed this way
                }
                catch (Exception)
                {

                    try
                    {
                        pictureBoxCover.Image = Image.FromFile(GeneralVars.DEFAULT_COVER_PATH);
                    }
                    catch (FileNotFoundException e)
                    {
                        MessageBox.Show("Default cover not found!" + e.Message, "Cover error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                }
            }

            //userInfo
            textBoxSeason.Text = serie.UserInfo.Season.ToString();
            textBoxEpisode.Text = serie.UserInfo.Episode.ToString();
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (!CheckErrors())
            {
                if(id == -1)
                {
                    serie = seriesData.Add(createWrapper());
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    //todo: Update Serie
                }
            }
            else
            {
                //todo: still errors
            }
        }


        private void textBoxTitel_Leave(object sender, EventArgs e)
        {
            //todo: async: start finding serie. catch the result
            startSearchIndicator();

            
            Thread searchThread = new Thread(delegate(object unused)
            {
                imdbServices.FindSeries(textBoxTitel.Text);
            });
            searchThread.IsBackground = true;
            searchThread.Name = "searchThread";
            searchThread.Start();
        }

        void imdbServices_FoundSeries(SeriesResultset M)
        {
            bool serieFound = false;
            bool moreResults = false;

            buttonSelectSerie.Visible = false; //reset visability for every search
            checkBoxAutoAirdates.Enabled = false;

            seriesResultset = M;
            if(!M.Any())
            {
                pictureBoxCover.Image = Properties.Resources.noImage;
                pictureBoxCover.Tag = "";

            }
            if(M.ExactMatches != null)
            {
                if (M.ExactMatches.Count == 1)
                {
                    imdbServices.GetSerieCoverAsyn(M.ExactMatches[0].Id, GetSerieCoverAsyncResult);
                    pictureBoxCover.Tag = M.ExactMatches[0].Id;
                    checkBoxAutoAirdates.Enabled = true;
                    serieFound = true;
                }
                else if( M.ExactMatches.Count > 1)
                {
                    moreResults = true;
                }
            }
            if(M.PopularTitles != null && !serieFound)
            {
                if (M.PopularTitles.Count == 1)
                {
                    imdbServices.GetSerieCoverAsyn(M.PopularTitles[0].Id, GetSerieCoverAsyncResult);
                    pictureBoxCover.Tag = M.PopularTitles[0].Id;
                    checkBoxAutoAirdates.Enabled = true;
                    serieFound = true;
                }
                else if(M.PopularTitles.Count > 1)
                {
                    moreResults = true;
                }
            }

            if(moreResults && !serieFound)
            {
                buttonSelectSerie.Enabled = true;
                buttonSelectSerie.Visible = true;
                pictureBoxCover.Image = Properties.Resources.MoreResult;
                pictureBoxCover.Tag = "";
            }
            
            stopSearchIndicator();

        }

        private void GetSerieCoverAsyncResult(Image result)
        {
            pictureBoxCover.Image = result;
        }

        private void startSearchIndicator()
        {
            //todo: get cover async
            pictureBoxCover.Controls.Add(progressIndicator);
            int progressIndex = pictureBoxCover.Controls.IndexOf(progressIndicator);
            pictureBoxCover.Controls[progressIndex].Location = new Point(68, 76);
            progressIndicator.Start();
        }

        private void stopSearchIndicator()
        {
            progressIndicator.Stop();
            pictureBoxCover.Controls.Remove(progressIndicator);
        }

        private void buttonSelectSerie_Click(object sender, EventArgs e)
        {
            SearchResultsForm srForm = new SearchResultsForm(seriesResultset);
            if(srForm.ShowDialog() == DialogResult.OK)
            {
                pictureBoxCover.Image = srForm.SerieCover;
                pictureBoxCover.Tag = srForm.SerieId;
                checkBoxAutoAirdates.Enabled = true;
            }
        }





        #region Update functions

        private bool picChange = false;



        private void checkForCover_Clicked(object sender, EventArgs e)
        {
            //FindCover();
            //checkBoxSaveCover.Visible = true;
            picChange = true;
        }


        //private void buttonUpdate_Click(object sender, EventArgs e)
        //{
        //    bool update = true;
        //    if (!CheckErrors())
        //    {
        //        if(picChange)
        //        {
        //            DialogResult messageResult =
        //                MessageBox.Show("Are you sure you don't want to save the new cover?", "Save cover?",//todo: do you want to save the new cover?
        //                                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
        //            if( messageResult == DialogResult.Yes)
        //            {
        //               coverStream = null; 
        //            } 
        //            else if(messageResult == DialogResult.Cancel)
        //            {
        //                update = false;
        //            }
        //        }
        //        if(update)
        //        {
        //            if(nextAirDate.Equals(DateTime.MinValue))
        //            {
        //                nextAirDate = serie.NextAirDate;
        //            }
        //            //seriesData.updateSerie(new Serie(textBoxTitel.Text, season, episode, nextAirDate,frequency, serie.CoverPath,curSeason,curEpisode,textBoxLocalDir.Text), selectedCollection, serie.Titel, coverStream);

        //            this.Dispose();
        //            reDrawScreen();   
        //        }
        //    }
        //}

        #endregion

        #region General functions

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonSetAirdate_Click(object sender, EventArgs e)
        {
            SetAirdateForm airdateForm = new SetAirdateForm(airInfo);
            airdateForm.ShowDialog();
        }

        /// <summary>
        /// Check form errors
        /// </summary>
        /// <returns>true: still errors</returns>
        private bool CheckErrors()
        {
            bool error = false;

            //------ check user info ------
            //title
            if (string.IsNullOrEmpty(textBoxTitel.Text))
            {
                errorProvider.SetError(textBoxTitel, "Enter a title please");
                error = true;
            }
            else
            {
                errorProvider.SetError(textBoxTitel, "");
            }
            //season
            if (Information.IsNumeric(textBoxSeason.Text))
            {
                season = int.Parse(textBoxSeason.Text);
                errorProvider.SetError(textBoxSeason, "");
            }
            else
            {
                error = true;
                errorProvider.SetError(textBoxSeason, "Enter a number");
            }
            //episode
            if (Information.IsNumeric(textBoxEpisode.Text))
            {
                episode = int.Parse(textBoxEpisode.Text);
                errorProvider.SetError(textBoxEpisode, "");
            }
            else
            {
                error = true;
                errorProvider.SetError(textBoxEpisode, "Enter a number");
            }

            return error;
        }


        private SerieWrapper createWrapper()
        {
            SerieUserInfo userInfo = new SerieUserInfo(season, episode);
            serie = new SerieWrapper(textBoxTitel.Text, (string) pictureBoxCover.Tag, pictureBoxCover.Image, textBoxLocalDir.Text, userInfo);
            if (!checkBoxAutoAirdates.Checked)
            {
                serie.AirInfo = airInfo;
                serie.AutoAirInfo = false;
            }
            
            return serie;
        }


        ///// <summary>
        ///// finds a cover based on the title, if found it will be saved in the coverstream (MemoryStream)
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="eventArgs"></param>
        ////todo: async
        //private void FindCover(object sender = null, EventArgs eventArgs = null)
        //{
        //    Cursor.Current = Cursors.WaitCursor;
        //    if (!String.IsNullOrEmpty(textBoxTitel.Text))
        //    {
        //        coverStream = seriesData.getCoverPic(textBoxTitel.Text);

        //        if (coverStream == null)
        //        {
        //            pictureBoxCover.Image = Image.FromFile(GeneralVars.DEFAULT_COVER_PATH);
        //            serie.CoverPath = null;
        //        }
        //        else
        //        {
        //            pictureBoxCover.Image = Image.FromStream(coverStream);
        //        }
        //    }
        //    FindCoverCompleted();
        //}


        private void FindCoverCompleted()
        {
            Cursor.Current = Cursors.Default;
        }

        private void buttonBrowseLocalDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFolderDialog = new FolderBrowserDialog();

            if (openFolderDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxLocalDir.Text = openFolderDialog.SelectedPath;
            }
        }

        private void checkBoxAutoAirdates_CheckedChanged(object sender, EventArgs e)
        {
            buttonSetAirdate.Enabled = !checkBoxAutoAirdates.Checked;
        }


    }

        #endregion

}
